import { useState, useEffect, useCallback, useRef, useContext } from "react";
import { Divider, Space, JumboTabs, Skeleton, Form, Input, Button, Modal } from 'antd-mobile';
import { KeyOutline, DownOutline, UpOutline, ChatAddOutline, PlayOutline, RedoOutline } from 'antd-mobile-icons';
import { SubTitle } from '../components/SubTitle';
import { useSelector, useDispatch } from 'react-redux';
import { setCurrQ, changeQ, fetchQs, fetchQAs } from '../slices/questionsSlice';
import { ActionCreators } from 'redux-undo';
import AuthContext from '../../../auth/AuthContext';
import introJs from 'intro.js';
import "./Qs.css";

export function Qs() {
  const dispatch = useDispatch();
  const currQ = useSelector(state => state.questions.present.currQ);
  const qs = useSelector(state => state.questions.present.qs);
  const qas = useSelector(state => state.questions.present.qas);
  const { me } = useContext(AuthContext);

  const [collapse, setCollapse] = useState(true);
  const [loadingQs, setLoadingQs] = useState(true);
  const [waittingConfirmQ, setWaittingConfirmQ] = useState(false);
  const triggeredByUndoRef = useRef(false);
  const qInputRef = useRef(null);
  useEffect(() => {
    if (qas) {
      if (!triggeredByUndoRef.current) {
        Modal.confirm({
          content: "更改问题需重新发送！",
          onConfirm: () => dispatch(changeQ()),
          onCancel: () => {
            dispatch(ActionCreators.undo());
            triggeredByUndoRef.current = true;
          }
        });
      } else {
        triggeredByUndoRef.current = false;
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currQ]);
  const getQs = useCallback(async () => {
    setLoadingQs(true);
    await dispatch(fetchQs());
    setLoadingQs(false);
  }, [dispatch]);
  useEffect(() => {
    async function init() {
      await getQs();
    }
    init();
  }, [getQs]);
  useEffect(() => {
    if (!loadingQs && me) {
      introJs().setOptions({
        nextLabel: '继续',
        prevLabel: '上一步',
        doneLabel: '好的',
        dontShowAgain: true,
        dontShowAgainLabel: '不再显示',
        steps: [
          {
            title: "欢迎来到品智教育咨询",
            intro: "您可以问我关于高中选科的问题哦！"
          },
          {
            element: document.querySelector('.confirmq-sub-title'),
            title: "确认问题",
            intro: "首先，明确您的问题。"
          },
          {
            element: document.querySelector('.qs'),
            title: "确认问题",
            intro: "如果您还不知道问什么，您可以在我思考提供的5个问题里选择。"
          },
          {
            element: document.querySelector('.q-inupt'),
            title: "确认问题",
            intro: "您也可以在这里输入您想到的问题。"
          },
          {
            element: document.querySelector('.q-send-button'),
            title: "发送问题",
            intro: "点击发送提问。"
          }
        ]
      }).onbeforeexit(() => {
        qInputRef.current.focus();
      }).start();
    }
  }, [loadingQs, me]);
  return (
    <>
      <SubTitle className="confirmq-sub-title" icon={<KeyOutline />} title="如您想问？" stitle="首先明确问题。" detail="选择一个合适的问题，或者自定义问题。"></SubTitle>
      <Divider style={{ margin: "8px 0" }}></Divider>
      {loadingQs ? (
        <><Skeleton.Title animated />
          <Skeleton.Paragraph lineCount={3} animated /></>
      ) : (
        <div style={{ borderRadius: '0.25rem', padding: '0.5rem', backgroundColor: '#f5f6f8' }}>
          <div style={{ fontSize: '14px' }} onClick={() => setCollapse(!collapse)}>
            {collapse ? <UpOutline /> : <DownOutline />}&nbsp;&nbsp;问题（{qs.length || 0}）
            <Button fill='none' size='mini' disabled={waittingConfirmQ} onClick={async (e) => {
              e.stopPropagation();
              dispatch(setCurrQ({ question: currQ.question }));
              getQs();
            }}><RedoOutline />&nbsp;换一批</Button>
          </div>
          {collapse && <div className='qs'>
            <JumboTabs activeKey={currQ && currQ.id + ""} onChange={key => { dispatch(setCurrQ(qs.find(q => q.id + "" === key))); }}>
              {qs.map((q, i) => {
                return (
                  <JumboTabs.Tab
                    title={<div style={{ whiteSpace: 'normal' }}><span style={{ fontWeight: 'bold' }}>{i + 1}</span><Divider style={{ borderColor: '#19556e', margin: '0 5px', borderWidth: 'medium' }} direction='vertical' />{q.question}</div>}
                    description={<div style={{ minWidth: '250px', whiteSpace: 'normal', width: 'unset' }}>{q.detail}</div>}
                    key={q.id + ""}
                    disabled={waittingConfirmQ} />
                );
              })}
            </JumboTabs>
          </div>}
        </div>
      )}
      <SubTitle icon={<ChatAddOutline />} title="确认问题 " stitle="AI交互分析。" detail="选择上面的一个问题或描述一个新的问题与我交互。"></SubTitle>
      <Form style={{ marginTop: '8px' }}>
        <Form.Item
          extra={<Button
            className="q-send-button"
            loading={waittingConfirmQ}
            disabled={!(currQ && currQ.question)}
            size='middle'
            style={{ backgroundColor: '#19556e', color: '#fff' }}
            onClick={async (e) => {
              setWaittingConfirmQ(true);
              await dispatch(fetchQAs());
              setWaittingConfirmQ(false);
            }}>
            <Space>
              <PlayOutline />
              <span>发送</span>
            </Space>
          </Button>}
        >
          <Input ref={qInputRef} className="q-inupt" autoFocus style={{ "border": "1px solid #ced4da", "borderRadius": "0.25rem", "padding": "5px 15px" }} disabled={waittingConfirmQ} placeholder='请输入问题' clearable value={currQ && currQ.question} onChange={(e) => {
            dispatch(setCurrQ({ question: e }));
          }} />
        </Form.Item>
      </Form>
    </>
  );
}
